// 购物车
import {ref,computed} from 'vue'
import {defineStore} from 'pinia'
import {useUserStore} from '@/stores/user'
import {addCartAPI,getCartAPI,deleteCartAPI} from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const cartList = ref([])
  const userStore = useUserStore()
  // 获取购物车列表
  const getCartList = async () => {
     const res= await getCartAPI()
    cartList.value = res.result
  }
  // 添加商品到购物车
  const addCart = async (goods) => {
    const item = cartList.value.find((item) => goods.skuId === item.skuId)
    if(userStore.userInfo.token){
      // 登录了  存储到数据库
      const {skuId,count} = goods
      await addCartAPI({skuId,count})
      await getCartList()
    }else{
      // 没有登录  本地存储
      // 判断购物车中是否已经存在该商品
      // 如果存在，则增加数量
      // 如果不存在，则添加到购物车
      if(item){
        item.count += goods.count
      }else{
        cartList.value.push(goods)
      }
    }
  }
  //删除购物车的商品
  const delCart = async (skuId) => {
    const index = cartList.value.findIndex((item) => skuId === item.skuId)
    // 判断是否登录
    if(userStore.userInfo.token){
      await deleteCartAPI([skuId])
      await getCartList()
    }else{
      //本地存储
      if(index !== -1){
        cartList.value.splice(index,1)
      }
    }
  }
  // 单选功能
  const singleCheck = (skuId) => {
    const item = cartList.value.find((item) => skuId === item.skuId)
    if(item){
      item.selected = !item.selected
    }
  }
  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  // 计算属性
  // 购物车中所有商品的数量
  const allCount = computed(() => {
    return cartList.value.reduce((p, c) => p + c.count, 0)
  })
  // 购物车中所有商品的总价
  const allPrice = computed(() => {
    return cartList.value.reduce((p, c) => p + c.count * c.price, 0)
  })
  //购物车中已选中商品的数量
  const selectedCount = computed(() => {
    return cartList.value.reduce((p, c) => p + (c.selected ? c.count : 0), 0)
  })
  //购物车中已选中商品的总价
  const selectedPrice = computed(() => {
    return cartList.value.reduce((p, c) => p + (c.selected ? c.count * c.price : 0), 0)
  })
//是否全选
  const isAll = computed(() => {
    return cartList.value.every((item) => item.selected)
  })

  return { cartList, getCartList,addCart,allCount ,allPrice,delCart,selectedCount,selectedPrice,singleCheck,isAll,clearCart}
},{ persist: true,})